import copy

from django import forms
from django.conf import settings
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from admin_interface.models import Theme

from .models import Link, Domain, Stat, Targeting, UTM
from .mixins import HideUserFieldMixin, ShowUserOwnDataMixin, HideDefaultDomainFieldMixin, ShowDefaultDomainsMixin


class UTMInline(admin.StackedInline):
    model = UTM
    max_num = 1
    verbose_name = _('UTM Builder (optional)')
    verbose_name_plural = _('UTM Builders')
    classes = ('collapse', 'extrapretty')


class TargetingInline(admin.TabularInline):
    model = Targeting
    extra = 1
    verbose_name = _('Targeting (optional)')
    verbose_name_plural = verbose_name
    classes = ('extrapretty',)

    def get_extra(self, req, obj=None, **kwargs):
        exrta = super().get_extra(req, obj, **kwargs)
        # obj is a Link instance.
        if obj and obj.targeting.count():
            return 0
        return exrta


@admin.register(Link)
class LinkAdmin(HideUserFieldMixin, ShowUserOwnDataMixin, admin.ModelAdmin):
    list_display = ('id', 'show_urls_with_title', 'get_status',
                    'clicks', 'created', 'show_actions')
    list_filter = ('status', 'user', 'created', 'updated')
    search_fields = ('title', 'slug', 'user__email')
    prepopulated_fields = {'slug': ('title',)}
    autocomplete_fields = ('user', 'domain')
    inlines = [
        UTMInline,
        TargetingInline,
    ]
    fieldsets = (
        (None, {
            'fields': ('link_type', 'title', 'domain', 'slug', 'original_url', 'status', 'password', 'user')
        }),
        (_('Schedule (optional)'), {
            'classes': ('collapse',),
            'fields': ('start_date', 'end_date')
        }),
        (_('Clicks Limit (optional)'), {
            'classes': ('collapse',),
            'fields': ('max_clicks', 'redirect_url')
        }),
    )
    date_hierarchy = 'created'


@admin.register(Domain)
class DomainAdmin(HideDefaultDomainFieldMixin, ShowDefaultDomainsMixin, HideUserFieldMixin,
                  ShowUserOwnDataMixin, admin.ModelAdmin):
    list_display = ('url', 'user', 'get_status',
                    'default', 'is_connected', 'created')
    search_fields = ('url',)
    list_filter = ('created', 'status')
    autocomplete_fields = ('user',)

    def has_change_permission(self, req, obj=None):
        if req.user.is_superuser:
            return True
        if obj and obj.user == req.user:
            return True
        return False

    def has_delete_permission(self, req, obj=None):
        if req.user.is_superuser:
            return True
        if obj and obj.user == req.user:
            return True
        return False


@admin.register(Stat)
class StatAdmin(admin.ModelAdmin):
    readonly_fields = ('ip', 'user', 'link', 'referer', 'city',
                       'country', 'region', 'browser', 'os', 'device', 'device_type')
    list_display = ('ip', 'country_flag', 'browser', 'os',
                    'device', 'link', 'created')
    search_fields = ('ip', 'link__slug')
    list_filter = ('browser', 'os', 'device', 'device_type', 'created')
    list_max_show_all = 200
    autocomplete_fields = ('user', 'link')
    date_hierarchy = 'created'

    fieldsets = (
        (None, {
            'fields': ('ip', 'link', 'user', 'referer')
        }),
        (_('Geo Location'), {
            'fields': ('city', 'region', 'country')
        }),
        (_('Device Info'), {
            'fields': ('device', 'device_type', 'browser', 'os')
        })
    )

    def has_add_permission(self, req, obj=None):
        return False


if settings.HIDE_MODELS:
    admin.site.unregister(Stat)
    # Unregister 'admin_interface' from dashboard.
    admin.site.unregister(Theme)
